<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_custom_model\validate;

use think\Db;
use think\Validate;

class AdminModelFieldValidate extends Validate
{
    protected $rule = [
        'field_name'       => 'require|regex:[a-zA-Z][a-zA-Z0-9_]*|checkFieldName',
        'field_nikename'       => 'require',
        'field_type'       => 'require',
    ];

    protected $message = [
        'field_name.require' => '字段名称必须填写',
        'field_name.regex' => '字段名称必须以英文字母开头，英文字母或数字或下划线组合',
        'field_nikename.require' => '字段别名必须填写',
        'field_type.require' => '字段类型必须填写',
    ];


    //自定义验证
    protected function checkFieldName($value,$rule,$data){
        if($value == 'id')
        {
            return '字段已存在！';
        }
        $fname = Db::name('model_field')->where(['model_id'=>$data['model_id'],'field_name'=>$data['field_name']])->select()->toArray();
        if(isset($data['oldname'])){
            if(($data['field_name']!=$data['oldname']) && $fname){
                return '字段已存在！';
            }
        }else{
            if($fname){
                return '字段已存在！';
            }
        }

        return true;
    }

}